package com.blog.filter;

import com.blog.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 校验用户是否登录：
 * 在用户访问后端的一些页面时，假如用户没有登录，跳转到用户登录页面、
 *
 * @author 黄嘉强
 */
@WebFilter(filterName = "loginFilter", urlPatterns = {"/admin.html", "/insertBanner.html", "/insertProduct.html"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        // 1. 获取HttpServletRequest和HttpServletResponse对象
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        // 2. 获取HttpSession对象，查看Session中有无User信息，如果没有，说明没有登录。
        HttpSession session = request1.getSession();
        User user = (User) session.getAttribute("u");
        if (user == null) {
            response1.sendRedirect("login.html");
            return;
        }

        // 3. 假如用户登录，则执行下一步
        chain.doFilter(request1, response1);
    }
}
